#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
批量修复render_to_response问题的脚本
"""
import os
import re
import glob

def fix_render_to_response_file(file_path):
    """修复单个文件中的render_to_response问题"""
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        original_content = content
        
        # 1. 修复 render_to_response 导入
        content = re.sub(
            r'from django\.shortcuts import ([^,\n]*,\s*)?render(request, [^, \n]*)',
            r'from django.shortcuts import \1render\2',
            content
        )
        
        # 2. 修复单独的 render_to_response 导入
        content = re.sub(
            r'from django\.shortcuts import render_to_response',
            'from django.shortcuts import render',
            content
        )
        
        # 3. 修复 render_to_response 调用，添加 request 参数
        # 匹配 render(request, 'template.html', context)
        content = re.sub(
            r'render_to_response\(([^,]+),\s*([^,]+),\s*context_instance\s*=\s*RequestContext\(request\)\)',
            r'render(request, \1, \2)',
            content
        )
        
        # 4. 修复 render(request, 'template.html', context)
        content = re.sub(
            r'render_to_response\(([^,]+),\s*([^)]+)\)',
            r'render(request, \1, \2)',
            content
        )
        
        # 5. 修复 render(request, 'template.html')
        content = re.sub(
            r'render_to_response\(([^)]+)\)', r'render(request, \1)',
            content
        )
        
        # 6. 添加 RequestContext 导入如果缺失
        if 'RequestContext' in content and 'from django.template import RequestContext' not in content:
            # 在其他导入之后添加
            import_section = re.search(r'(from django\.shortcuts import[^\n]*\n)', content)
            if import_section:
                content = content.replace(
                    import_section.group(1),
                    import_section.group(1) + 'from django.template import RequestContext\n'
                )
        
        # 只有在内容发生变化时才写入文件
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"✓ 修复完成: {file_path}")
            return True
        else:
            return False
            
    except Exception as e:
        print(f"✗ 修复失败 {file_path}: {e}")
        return False

def main():
    """主函数"""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    
    print("开始批量修复render_to_response问题...")
    print("=" * 50)
    
    # 获取所有Python文件
    python_files = []
    for root, dirs, files in os.walk(base_dir):
        # 跳过某些目录
        dirs[:] = [d for d in dirs if d not in ['__pycache__', '.git', 'static', 'media']]
        
        for file in files:
            if file.endswith('.py'):
                file_path = os.path.join(root, file)
                # 检查文件是否包含render_to_response
                try:
                    with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                        content = f.read()
                        if 'render_to_response' in content:
                            python_files.append(file_path)
                except:
                    pass
    
    print(f"找到 {len(python_files)} 个需要修复的文件")
    
    # 修复文件
    fixed_count = 0
    failed_count = 0
    
    for file_path in python_files:
        try:
            if fix_render_to_response_file(file_path):
                fixed_count += 1
        except Exception as e:
            print(f"✗ 处理文件失败 {file_path}: {e}")
            failed_count += 1
    
    print("=" * 50)
    print(f"修复完成！")
    print(f"✓ 成功修复: {fixed_count} 个文件")
    print(f"✗ 失败: {failed_count} 个文件")
    print(f"总计处理: {len(python_files)} 个文件")

if __name__ == "__main__":
    main() 